<template>
  <div class="app-container">
    <div>
      <p class="dialogTitle title">当前地震事件: 
        <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
        <span v-else>请在地震事件管理中设置当前地震事件</span>
      </p>
    </div>

    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px" v-show="showSearch">
      <el-form-item label="物资名称" prop="materialName">
          <el-input v-model="queryParams.materialName" placeholder="请输入物资名称"  clearable />
      </el-form-item>
      <el-form-item label="物资类型" prop="category">
          <el-input v-model="queryParams.category" placeholder="请输入物资类型"  clearable />
      </el-form-item>
      <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
            <el-button type="primary" :disabled="!currentEvent" @click="handleImport">导入</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="primary" :disabled="!currentEvent" @click="handleAdd">新建</el-button>
        </el-col>
    </el-row>

    <el-table v-loading="loading" :data="dataList" stripe>
        <el-table-column label="序号" align="center" width="55">
          <template #default="scope">
            <span>{{(queryParams.page - 1) * queryParams.rows + scope.$index + 1}}</span>
          </template>             
        </el-table-column>
        <el-table-column label="物资编号" align="center" prop="materialCode">
          <template #default="scope">
            <span style="color: #107ce1;cursor: pointer;" @click="handleEdit(scope.row)">{{ scope.row.materialCode }}</span>
          </template>   
        </el-table-column>
        <el-table-column label="物资名称" align="center" prop="materialName" width="150px"/>
        <el-table-column label="物资类型" align="center" prop="category" />
        <el-table-column label="物资数量" align="center" prop="quantity" />
        <el-table-column label="创建单位" align="center" prop="createUnit" />
        <el-table-column label="创建人" align="center" prop="createUserName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">     
			      <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"   @pagination="getList" /> 
      
    <el-dialog :title="title" v-model="open" width="630px" append-to-body>
      <el-form ref="addRef" label-width="120px" :model="form" :rules="rules">
        <el-row style="margin: 20px 0;">        
            <el-col>
              <el-form-item label="物资编号" prop="materialCode" required>
                <el-input v-model="form.materialCode" placeholder="请输入物资编号"  disabled />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="物资名称" prop="materialName">
                <el-input v-model="form.materialName" placeholder="请输入物资名称"   clearable show-word-limit  maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="物资类型" prop="category">
                <el-input v-model="form.category" placeholder="请输入物资类型" clearable/>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="物资数量" prop="quantity">
                <el-input v-model="form.quantity" placeholder="请输入物资数量"  clearable />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="描述信息" prop="commentInfo">
                <el-input v-model="form.commentInfo" type="textarea" maxlength="500" show-word-limit :autosize="{ minRows: 5, maxRows: 5 }" placeholder="请输入描述信息" clearable/>
              </el-form-item>
            </el-col>            
            <el-col>
              <el-form-item label="创建人单位" prop="createUnit" required>
                <el-input v-model="form.createUnit" placeholder="请输入创建人单位"  disabled />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="创建人" prop="createUserName" required>
                <el-input v-model="form.createUserName" placeholder="请输入创建人"  disabled />
              </el-form-item>
            </el-col>            
            <el-col>
              <el-form-item label="创建时间" prop="createTime" required>
                <el-input v-model="form.createTime" placeholder="请输入创建时间"  disabled />
              </el-form-item>
            </el-col>

        </el-row>         
      </el-form>
      <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="save">保 存</el-button>
              <el-button @click="open = false">取 消</el-button>
          </div>
      </template>
    </el-dialog>    
      <!-- 导入对话框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
          <p></p>
          <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
              :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
              :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError" :on-success="handleFileSuccess"
              :data="{ 'xsemId': currentEvent.id }" :auto-upload="false" drag>
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                  <div class="el-upload__tip text-center">
                      <span>仅允许导入xls、xlsx格式文件。</span>
                       <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                          @click="importTemplate('物资导入模板.xlsx')">下载模板</el-link> 
                  </div>
              </template>
          </el-upload>
          <template #footer>
              <div class="dialog-footer">
                  <el-button type="primary" @click="submitFileForm">确 定</el-button>
                  <el-button @click="upload.open = false">取 消</el-button>
              </div>
          </template>
        </el-dialog>    
  </div>
</template>

<script setup name="goodsManagee">
import useEventStore from "@/store/modules/event";
import { getToken } from "@/utils/auth";
import { getAllList, saveData, getDetail, updateData ,getHeadCode, del,importExcel } from "@/api/comprehensiveInformation/goodsManagee.js"
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const loading = ref(false);
const total = ref(0);
const showSearch = ref(true);
const open = ref(false);
const title = ref();

const currentEvent = computed(() => useEventStore().currentEvent);
/*** 导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "token " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/matManage/importExcel"
});
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        materialName: undefined,
        category: undefined,
    },
    form: {
    },
    rules: {
      materialName:[{ required: true, message: "物资名称不能为空", trigger: "blur" }],
      category:[{ required: true, message: "物资类型不能为空", trigger: "blur" }],
      quantity:[{ required: true, message: "数量不能为空", trigger: "blur" }],
    }
})
const { queryParams, form, rules } = toRefs(data)

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() { 
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

// 获取getHeadCode信息
function getHeaderData(){
  getHeadCode({eventCode:currentEvent.value.eventCode}).then(res=>{
    open.value = true;
    proxy.resetForm("addRef");
    form.value = res.data;
    form.value.materialCode=res.data.headCode;
  })
}
// 导出模版
function importTemplate(name) {
    proxy.downloadTemplate("/template/download", {
        fileName: name
    }, name);
};
// 导入
function handleImport(){
  upload.title = "导入";
  upload.open = true;
}
/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};
/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$modal.closeLoading();
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +  response.data?response.data:response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
};
// 新增
function handleAdd(){
  title.value = '新建物资信息';
  getHeaderData()
}
// 编辑 
function handleEdit(row){
  title.value = '编辑物资信息'
  detail(row.xmmId);
}
// 查看
function detail(id){
  getDetail({id:id}).then(res=>{
    open.value = true;
    proxy.resetForm("addRef");
    form.value = res.data;
  })
}
// 保存
function save(){
  proxy.$refs["addRef"].validate(valid => {
    if (valid) {
      if(title.value=='新建物资信息'){
        saveData({...form.value,xsemId:currentEvent.value.id}).then(res=>{
          proxy.$modal.msgSuccess("新建成功");
          open.value = false;
          getList();
        })
      }else{
        updateData({...form.value}).then(res=>{
          proxy.$modal.msgSuccess("保存成功");
          open.value = false;
          getList();
        })
      }
    }
  })

}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
			.confirm("是否确认删除该信息，请确认是否要删除？", )
			.then(function() {
				return del(row.xmmId);
			})
			.then(() => {
				getList();
				proxy.$modal.msgSuccess("删除成功");
			})
			.catch(() => {});
}

/** 查询数据列表 */
function getList() {
  if(currentEvent.value){
    loading.value = true;
    getAllList({...queryParams.value,xsemId:currentEvent.value.id}).then(response => {
        dataList.value = response.data.rows ? response.data.rows : [];
        total.value = response.data.total;
        loading.value = false;
    }).catch(err=>{loading.value = false});
  }else{
    dataList.value = [];
    total.value = 0;
  }
}

onMounted(() => {
  setTimeout(()=>{
    getList();
  },200)
})
</script>

<style scoped lang="scss">
.title{
  margin: 0 0 20px!important;
}
</style>

